const koa = require('koa')
const router = require('koa-router')()
const views = require('koa-views')
const static = require('koa-static')
const bodyParser = require('koa-bodyparser')
const multer = require('koa-multer')
const path = require('path')
const fs = require('fs')
const md5 = require('md5');
const moveFile = require('move-file');
const { delDir } = require('./util/index');


const tempDir = path.resolve(__dirname,"./static/tempDir");
const chunkDir = path.resolve(__dirname,"./static/chunkDir");
const uploadDir =  path.resolve(__dirname,"./static/upload");

// 如果必要的文件上传目录不存在,则创建之
if (!fs.existsSync(uploadDir)) {
    fs.mkdirSync(uploadDir, 0777);
}
if (!fs.existsSync(tempDir)) {
    fs.mkdirSync(tempDir, 0777);
}
if (!fs.existsSync(chunkDir)) {
    fs.mkdirSync(chunkDir, 0777);
}

const app = new koa();

app.use(bodyParser())

app.use(static(path.resolve(__dirname,'./static')));

app.use(views(path.resolve(__dirname,'./views'),{
    map:{
     'html':'ejs'
    }
}))

router.get('/',async ctx =>{
    await ctx.render('index');
});

router.post('/fileupload', multer({dest: tempDir}).array('file'), async ctx =>{

        var src_path = ctx.req.files[0].path;// 原始片段在临时目录下的路径
        var des_dir = [chunkDir, ctx.req.body.guid].join('\\');
        var des_path = (ctx.req.body.chunk) ? [des_dir, ctx.req.body.chunk].join('\\') : des_dir;


        // 如果没有des_dir目录,则创建des_dir
        if (!fs.existsSync(des_dir)) {
            fs.mkdirSync(des_dir);
        }
 
        // 移动分片文件到
        try {
           
            await moveFile(src_path,des_path);

            // ctx.state = 200;
            ctx.body ={'status': 1, 'msg': ctx.req.body.guid + '_' + ctx.req.body.chunk + '上传成功!'}
            
        } catch (e) {
            console.log(e);
            return ctx.body({'status': 0, 'msg': '移动分片文件错误!'});
        }

});

router.post('/merge_chunks',async ctx=>{
   
    console.log(ctx.request.body);
   
    const src_dir = [ chunkDir, ctx.request.body.hash + '/'].join('/');
    

    // 目标目录
    var time = new Date();
    var ddpath = [
        time.getFullYear(),
        time.getMonth() + 1 <= 9 ? '0' + (time.getMonth() + 1) : time.getMonth() + 1,
    ].join('');// 文件目录名
 
    // 如果没有des_dir目录,则创建des_dir
    var des_dir = [uploadDir, ddpath].join('/');
    if (!fs.existsSync(des_dir)) {
        fs.mkdirSync(des_dir);
    }

    // 文件名+扩展名
    var name = decodeURIComponent(ctx.request.body.name);

    // 文件的实际名称和路径
    var fileName = md5([ddpath, name, ctx.request.body.size, new Date().getTime(), 99999 * Math.random()].join('fileSalt'));

    // 文件签名
    var sig = md5([ddpath, name, fileName, ctx.request.body.size].join('fileSalt'));

    // 文件的实际路径
    var des_path = [des_dir, fileName].join('/');

    try {
        var files = fs.readdirSync(src_dir);

        if (files.length == 0) {
            ctx.state = 404;
            return ctx.body ={'status': 0, 'url': '', 'msg': '分片文件不存在!'};
        }

        if (files.length > 1) {
            files.sort(function (x, y) {
                return x - y;
            });
        }

        for (var i = 0, len = files.length; i < len; i++) {
            fs.appendFileSync(des_path, fs.readFileSync(src_dir + files[i]));
        }

        // 删除分片文件夹
        delDir(src_dir)

        return ctx.body = ({
            'status': 1,
            'url': [
                'http://127.0.0.1:6888',
                'file', fileName,
                'path', ddpath,
                'name', encodeURIComponent(name),
                'sig', sig
            ].join('/')
        });
    } catch (e) {
        // 删除分片文件夹
        console.log(e);
        delDir(src_dir)

        return ctx.body ={'status': 0, 'url': ''};
    }

});

app.use(router.routes()).use(router.allowedMethods());

app.listen(3000,function(){
    console.log('服务器启动在3000...')
})

